import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import xyz.chaobei.common.Student;

import java.io.*;
import java.util.Objects;

/**
 * 测试输入流
 *
 * @author <a href='mailto:maruichao52@gmail.com'>MRC</a>
 * @since 2020/11/24
 */
@Slf4j
public class TestInputStream {
    /**
     * <p> 创建一个文件
     * <p>author: <a href='mailto:maruichao52@gmail.com'>MRC</a>
     *
     * @return java.io.File
     * @since 2020/11/24
     **/
    @Test
    public void createNewFile() {

        final String FILE_PATH = "D:\\test.txt";
        File file = new File(FILE_PATH);

        log.info("file exits={}", file.exists());
        log.info("file path={}", file.getPath());
        log.info("file name={}", file.getName());
        log.info("file is file={}", file.isFile());

        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void testByteArray() throws IOException {
        // 使用字节数组来模拟一个InputStream
        String desc = "hello byteArrayInputStream";

        InputStream byteArray = new ByteArrayInputStream(desc.getBytes());

        byte[] bytes = new byte[8];
        int num = 0;
        while ((num = byteArray.read(bytes)) != -1) {
            log.info("read num={}", num);
            log.info("read string={}", new String(bytes, 0, num));
        }
        byteArray.close();
    }

    @Test
    public void testFileInput() {
        final String FILE_PATH = "D:\\test.txt";
        try (InputStream input = new FileInputStream(FILE_PATH)) {

            byte buffer[] = new byte[1024];
            int num;
            while ((num = input.read(buffer)) != -1) {
                System.out.println("读取字符量：" + num);
                String s = new String(buffer, 0, num);
                System.out.println(s);
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    @Test
    public void testObjectInput() throws IOException {

        final String FILE_PATH = "D:\\obj.dat";

        FileInputStream fileInputStream = null;
        ObjectInputStream inputStream = null;

        try {
            File file = new File(FILE_PATH);
            log.info("file size={}", file.length());
            log.info("file name={}", file.getName());

            fileInputStream = new FileInputStream(file);
            inputStream = new ObjectInputStream(fileInputStream);

            Student student1 = (Student) inputStream.readObject();
            log.info("student info={}", JSON.toJSONString(student1));
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {

            if (Objects.isNull(inputStream)) {
                inputStream.close();
            }
            if (Objects.nonNull(fileInputStream)) {
                fileInputStream.close();
            }

        }
    }


}
